package com.alogic.es.xscript;

import com.alogic.es.core.Indexer;
import com.alogic.remote.Client;
import com.alogic.remote.Request;
import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsObject;
import com.anysoft.util.IOTools;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;

/**
 * http request
 *
 * @since 1.6.13.9 [20200824 duanyy]
 */
public class EsRequest extends NS {
    /**
     * 缺省的method
     */
    public static final String DFT_METHOD = "POST";

    /**
     * 输出对象的上下文id
     */
    protected String cid = "remote-req";

    /**
     * 客户端id，从Context中获取
     */
    protected String pid = "$es-indexer";

    /**
     * method
     */
    protected String $method = DFT_METHOD;

    protected String $debug = "false";

    public EsRequest(String tag, Logiclet p) {
        super(tag, p);
    }

    @Override
    public void configure(Properties p){
        super.configure(p);

        cid = PropertiesConstants.getString(p, "cid", cid,true);
        pid = PropertiesConstants.getString(p, "pid", pid);
        $method = PropertiesConstants.getRaw(p, "method", $method);
        $debug = PropertiesConstants.getRaw(p,"debug",$debug);
    }

    @Override
    protected void onExecute(XsObject root, XsObject current, LogicletContext ctx, ExecuteWatcher watcher) {
        Indexer indexer = ctx.getObject(pid);
        if (indexer != null){
            Client client = indexer.getRemoteClient();
            if (client != null){
                Request req = null;
                try {
                    req = client.build(
                            PropertiesConstants.transform(ctx,$method,DFT_METHOD),
                            PropertiesConstants.transform(ctx,$debug,false)
                    );
                    ctx.setObject(cid, req);
                    super.onExecute(root, current, ctx, watcher);
                }finally{
                    ctx.removeObject(cid);
                    IOTools.close(req);
                }
            }else{
                log(String.format("[%s] Indexer remote client is not found,pid = %s",this.getXmlTag(),pid),"warning");
            }
        }else{
            log(String.format("[%s] Indexer is not found,pid = %s",this.getXmlTag(),pid),"warning");
        }
    }
}
